#include <QDebug>
#include <QMatrix>
#include "customqgraphicsview.h"

CustomQGraphicsView::CustomQGraphicsView(QWidget *parent)
    : QGraphicsView(parent)
{

}

CustomQGraphicsView::~CustomQGraphicsView()
{

}

void CustomQGraphicsView::zoom(bool zoomIn)
{
    qreal sMin;
    qreal sMax;
    getMinMaxSizeSxSy(sMin, sMax);
    qreal step = (sMax - sMin)/10.0;
    QMatrix mat = matrix();

    qreal curScale = mat.m11();

    qreal newScale = zoomIn ? (curScale - step) : (curScale + step);

    if(newScale < sMin){
        newScale = sMin;
    } else if (newScale > sMax){
        newScale = sMax;
    }

    mat.setMatrix(newScale, mat.m12(), mat.m21(), newScale,  mat.dx(), mat.dy());
    setMatrix(mat);

    qDebug()<<"zoom"<<zoomIn<<"scale"<<newScale;
}

void CustomQGraphicsView::getMinMaxSizeSxSy(qreal &sMin, qreal &sMax)
{
    QRectF sceneRect = scene()->sceneRect();
    qDebug()<<"getMinMaxSizeSxSy scenceRect"<<sceneRect;
    qDebug()<<"getMinMaxSizeSxSy widget size "<<width()<<height();
    qreal minSx = (width() - 2) / sceneRect.width();
    qreal minSy = (height() - 2) / sceneRect.height();
    sMin = qMin(minSx, minSy);

    qreal maxSx = (qreal)(width() - 2) / 1920.0 * 2.0;
    qreal maxSy = (qreal)(height() - 2) / 1080.0 * 2.0;

    sMax = qMin(maxSx, maxSy);

    qDebug()<<"getMinMaxSizeSxSy sMin"<<sMin<<"sMax"<<sMax;
}

void CustomQGraphicsView::smallest()
{
    qreal sMin;
    qreal sMax;
    getMinMaxSizeSxSy(sMin, sMax);

    QMatrix mat = matrix();
    mat.setMatrix(sMin, mat.m12(), mat.m21(), sMin,  mat.dx(), mat.dy());
    setMatrix(mat);
}

//void CustomQGraphicsView::resizeEvent(QResizeEvent *event)
//{
//    QGraphicsView::resizeEvent(event);

//    QMatrix mat = matrix();
//    qDebug()<<"resizeEvent resize sx"<<mat.m11()<<"sy"<<mat.m22();
//    qDebug()<<"resizeEvent view size "<<width()<<height();

//    QRectF rect = scene()->sceneRect();
//    qDebug()<<"resizeEvent sence size "<< rect.width() << rect.height();

//     smallest();
//}

//void CustomQGraphicsView::showEvent(QShowEvent *event)
//{
//    //    fitInView(scene()->sceneRect(), Qt::KeepAspectRatio);
//    QMatrix mat = matrix();
//    qDebug()<<"showEvent show event resize sx"<<mat.m11()<<"sy"<<mat.m22();


//    QMatrix mat1 = matrix();
//    qDebug()<<"showEvent show event 1 resize sx"<<mat1.m11()<<"sy"<<mat1.m22();
//}

